<?php

namespace App\Events;

use App\Models\Machine;
use App\Services\EchoServer;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * 游戏进入下一局
 *
 * Class GameNextTurn
 * @package App\Events
 */
class GameNextTurn implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
    
    /**
     * 游戏机
     *
     * @var \App\Models\Machine
     */
    protected $machine;
    
    /**
     * 频道名称
     *
     * @var string
     */
    protected $channel;
    
    public function __construct(Machine $machine)
    {
        $this->machine = $machine;
    
        $this->channel = "machines.{$this->machine->id}.player_queue";
    }

    /**
     * 广播频道：machines.{machine_id}.player_queue
     *
     * @return \Illuminate\Broadcasting\PresenceChannel
     */
    public function broadcastOn()
    {
        return new PresenceChannel($this->channel);
    }
    
    /**
     * 事件名：game.next.turn
     *
     * @return string
     */
    public function broadcastAs()
    {
        return snake_case(class_basename(self::class), '.');
    }
    
    /**
     * 事件参数
     *
     * @return array
     */
    public function broadcastWith()
    {
        /** @var EchoServer $echoServer */
        $echoServer = app(EchoServer::class);
        $members = $echoServer->getMembers($this->channel);
        
        // 获取第一个排队用户
        return [
            'user_id' => empty($members) ? 0 : $members[0]['user_id'],
        ];
    }
}
